package pe.edu.unmsm.cinfo.siga.ui.ventanas;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import javax.persistence.RollbackException;
import javax.swing.JOptionPane;
import org.eclipse.persistence.exceptions.DatabaseException;
import org.jdesktop.application.Action;
import pe.edu.unmsm.cinfo.siga.datos.Docente;

/**
 * @author Juan
 */
public class AdministrarDocentesInternalFrame extends javax.swing.JInternalFrame {

   /** Creates new form AdministrarDocentesInternalFrame */
   //constructors
   public AdministrarDocentesInternalFrame() {
      initComponents();
   }
   //methods
   /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    */
   @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(pe.edu.unmsm.cinfo.siga.ui.Main.class).getContext().getResourceMap(AdministrarDocentesInternalFrame.class);
        entityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory(resourceMap.getString("entityManager.persistenceUnit")).createEntityManager(); // NOI18N
        docenteQuery = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery(resourceMap.getString("docenteQuery.query")); // NOI18N
        docenteList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(docenteQuery.getResultList());
        docenteSeleccionado = null;
        totalPanel = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        buscarComboBox = new javax.swing.JComboBox();
        buscarTextField = new javax.swing.JTextField();
        tabbedPane = new javax.swing.JTabbedPane();
        relacionPanel = new javax.swing.JPanel();
        scrollPane = new javax.swing.JScrollPane();
        tabla = new javax.swing.JTable();
        editarPanel = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        codigoTextField = new javax.swing.JTextField();
        nombreTextField = new javax.swing.JTextField();
        direccionTextField = new javax.swing.JTextField();
        tlfTextField = new javax.swing.JTextField();
        editarButton = new javax.swing.JButton();
        grabarButton = new javax.swing.JButton();
        nuevoButton = new javax.swing.JButton();
        eliminarButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();

        setClosable(true);
        setIconifiable(true);
        setMaximizable(true);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setName("Form"); // NOI18N

        totalPanel.setName("totalPanel"); // NOI18N

        jLabel1.setFont(resourceMap.getFont("jLabel1.font")); // NOI18N
        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        buscarComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Código", "Nombre" }));
        buscarComboBox.setName("buscarComboBox"); // NOI18N

        buscarTextField.setText(resourceMap.getString("buscarTextField.text")); // NOI18N
        buscarTextField.setName("buscarTextField"); // NOI18N
        buscarTextField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                buscarTextFieldKeyTyped(evt);
            }
        });

        tabbedPane.setName("tabbedPane"); // NOI18N
        tabbedPane.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tabbedPaneMouseClicked(evt);
            }
        });

        relacionPanel.setName("relacionPanel"); // NOI18N

        scrollPane.setName("scrollPane"); // NOI18N

        tabla.setAutoCreateRowSorter(true);
        tabla.setName("tabla"); // NOI18N
        tabla.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        tabla.getTableHeader().setResizingAllowed(false);
        tabla.getTableHeader().setReorderingAllowed(false);

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, docenteList, tabla);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${doceCod}"));
        columnBinding.setColumnName("Doce Cod");
        columnBinding.setColumnClass(Integer.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${doceNom}"));
        columnBinding.setColumnName("Doce Nom");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${docenteSeleccionado}"), tabla, org.jdesktop.beansbinding.BeanProperty.create("selectedElement"), "");
        bindingGroup.addBinding(binding);

        tabla.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tablaMouseClicked(evt);
            }
        });
        scrollPane.setViewportView(tabla);
        tabla.getColumnModel().getColumn(0).setResizable(false);
        tabla.getColumnModel().getColumn(0).setPreferredWidth(50);
        tabla.getColumnModel().getColumn(0).setHeaderValue(resourceMap.getString("tabla.columnModel.title0")); // NOI18N
        tabla.getColumnModel().getColumn(1).setResizable(false);
        tabla.getColumnModel().getColumn(1).setPreferredWidth(300);
        tabla.getColumnModel().getColumn(1).setHeaderValue(resourceMap.getString("tabla.columnModel.title1")); // NOI18N

        javax.swing.GroupLayout relacionPanelLayout = new javax.swing.GroupLayout(relacionPanel);
        relacionPanel.setLayout(relacionPanelLayout);
        relacionPanelLayout.setHorizontalGroup(
            relacionPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(scrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 596, Short.MAX_VALUE)
        );
        relacionPanelLayout.setVerticalGroup(
            relacionPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(scrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 311, Short.MAX_VALUE)
        );

        tabbedPane.addTab(resourceMap.getString("relacionPanel.TabConstraints.tabTitle"), relacionPanel); // NOI18N

        editarPanel.setName("editarPanel"); // NOI18N

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N

        jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
        jLabel4.setName("jLabel4"); // NOI18N

        jLabel5.setText(resourceMap.getString("jLabel5.text")); // NOI18N
        jLabel5.setName("jLabel5"); // NOI18N

        codigoTextField.setEditable(false);
        codigoTextField.setName("codigoTextField"); // NOI18N

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, this, org.jdesktop.beansbinding.ELProperty.create("${docenteSeleccionado.doceCod}"), codigoTextField, org.jdesktop.beansbinding.BeanProperty.create("text"));
        binding.setSourceNullValue("");
        binding.setSourceUnreadableValue("");
        bindingGroup.addBinding(binding);

        nombreTextField.setName("nombreTextField"); // NOI18N

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, this, org.jdesktop.beansbinding.ELProperty.create("${docenteSeleccionado.doceNom}"), nombreTextField, org.jdesktop.beansbinding.BeanProperty.create("text"));
        binding.setSourceNullValue(null);
        binding.setSourceUnreadableValue(null);
        bindingGroup.addBinding(binding);

        direccionTextField.setName("direccionTextField"); // NOI18N

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, this, org.jdesktop.beansbinding.ELProperty.create("${docenteSeleccionado.doceDir}"), direccionTextField, org.jdesktop.beansbinding.BeanProperty.create("text"));
        binding.setSourceNullValue(null);
        binding.setSourceUnreadableValue(null);
        bindingGroup.addBinding(binding);

        tlfTextField.setName("tlfTextField"); // NOI18N

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, this, org.jdesktop.beansbinding.ELProperty.create("${docenteSeleccionado.doceTel1}"), tlfTextField, org.jdesktop.beansbinding.BeanProperty.create("text"));
        binding.setSourceNullValue(null);
        binding.setSourceUnreadableValue(null);
        bindingGroup.addBinding(binding);

        javax.swing.GroupLayout editarPanelLayout = new javax.swing.GroupLayout(editarPanel);
        editarPanel.setLayout(editarPanelLayout);
        editarPanelLayout.setHorizontalGroup(
            editarPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, editarPanelLayout.createSequentialGroup()
                .addContainerGap(132, Short.MAX_VALUE)
                .addGroup(editarPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(jLabel4)
                    .addComponent(jLabel3)
                    .addComponent(jLabel5))
                .addGap(18, 18, 18)
                .addGroup(editarPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(nombreTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 295, Short.MAX_VALUE)
                    .addComponent(direccionTextField)
                    .addComponent(tlfTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(codigoTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(104, 104, 104))
        );
        editarPanelLayout.setVerticalGroup(
            editarPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(editarPanelLayout.createSequentialGroup()
                .addGap(80, 80, 80)
                .addGroup(editarPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(codigoTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addGap(18, 18, 18)
                .addGroup(editarPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(nombreTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addGap(18, 18, 18)
                .addGroup(editarPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(direccionTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(editarPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tlfTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addContainerGap(97, Short.MAX_VALUE))
        );

        tabbedPane.addTab(resourceMap.getString("editarPanel.TabConstraints.tabTitle"), editarPanel); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(pe.edu.unmsm.cinfo.siga.ui.Main.class).getContext().getActionMap(AdministrarDocentesInternalFrame.class, this);
        editarButton.setAction(actionMap.get("editarButtonActionPerformed")); // NOI18N
        editarButton.setIcon(resourceMap.getIcon("editarButton.icon")); // NOI18N
        editarButton.setText(resourceMap.getString("editarButton.text")); // NOI18N
        editarButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        editarButton.setName("editarButton"); // NOI18N
        editarButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);

        grabarButton.setAction(actionMap.get("grabarButtonActionPerformed")); // NOI18N
        grabarButton.setIcon(resourceMap.getIcon("grabarButton.icon")); // NOI18N
        grabarButton.setText(resourceMap.getString("grabarButton.text")); // NOI18N
        grabarButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        grabarButton.setName("grabarButton"); // NOI18N
        grabarButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);

        nuevoButton.setAction(actionMap.get("nuevoButtonActionPerformed")); // NOI18N
        nuevoButton.setIcon(resourceMap.getIcon("nuevoButton.icon")); // NOI18N
        nuevoButton.setText(resourceMap.getString("nuevoButton.text")); // NOI18N
        nuevoButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        nuevoButton.setName("nuevoButton"); // NOI18N
        nuevoButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);

        eliminarButton.setAction(actionMap.get("eliminarButtonActionPerformed")); // NOI18N
        eliminarButton.setIcon(resourceMap.getIcon("eliminarButton.icon")); // NOI18N
        eliminarButton.setText(resourceMap.getString("eliminarButton.text")); // NOI18N
        eliminarButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        eliminarButton.setName("eliminarButton"); // NOI18N
        eliminarButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);

        cancelButton.setAction(actionMap.get("cancelarButtonActionPerformed")); // NOI18N
        cancelButton.setIcon(resourceMap.getIcon("cancelButton.icon")); // NOI18N
        cancelButton.setText(resourceMap.getString("cancelButton.text")); // NOI18N
        cancelButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        cancelButton.setName("cancelButton"); // NOI18N
        cancelButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);

        javax.swing.GroupLayout totalPanelLayout = new javax.swing.GroupLayout(totalPanel);
        totalPanel.setLayout(totalPanelLayout);
        totalPanelLayout.setHorizontalGroup(
            totalPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(totalPanelLayout.createSequentialGroup()
                .addGroup(totalPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(totalPanelLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(tabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 601, Short.MAX_VALUE))
                    .addGroup(totalPanelLayout.createSequentialGroup()
                        .addGap(28, 28, 28)
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(buscarComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(buscarTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 277, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, totalPanelLayout.createSequentialGroup()
                .addContainerGap(114, Short.MAX_VALUE)
                .addComponent(nuevoButton, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(editarButton, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(grabarButton, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(eliminarButton, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cancelButton)
                .addGap(85, 85, 85))
        );
        totalPanelLayout.setVerticalGroup(
            totalPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(totalPanelLayout.createSequentialGroup()
                .addGroup(totalPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(totalPanelLayout.createSequentialGroup()
                        .addGap(24, 24, 24)
                        .addGroup(totalPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(buscarComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(buscarTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(totalPanelLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(18, 18, 18)
                .addComponent(tabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 339, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(totalPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(totalPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE, false)
                        .addComponent(grabarButton, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(cancelButton, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(eliminarButton, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(editarButton, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(nuevoButton, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(totalPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(totalPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents
   @Action
   private void buscarTextFieldKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_buscarTextFieldKeyTyped
      try{
         tabla.clearSelection();
         if(buscarTextField.getText().isEmpty())   return;
         String buscarPor = (String)buscarComboBox.getSelectedItem();
         String nomColumna;
         int index;
         for(index = 0; index < tabla.getColumnCount(); index++){
            nomColumna = (String)tabla.getColumnModel().getColumn(index).getHeaderValue();
            if(buscarPor.equals(nomColumna)) break;
         }
         if(index == tabla.getColumnCount()) throw new Exception("Busqueda no valida");
         for(int i = 0; i < tabla.getRowCount(); i++){
            if(textContenidoEn(tabla.getValueAt(i, index))){
               mostrarFila(i);
               break;
            }
         }
      }catch(Exception e){
         JOptionPane.showMessageDialog(this, e.getMessage() + "...!");
      }
   }//GEN-LAST:event_buscarTextFieldKeyTyped

   private void mostrarFila(int fila){
      tabla.setRowSelectionInterval(fila, fila);
      tabla.scrollRectToVisible(tabla.getCellRect(fila, 0, true));
   }
   @Action
   private void tablaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tablaMouseClicked
      editarButton.setEnabled(true);
      eliminarButton.setEnabled(true);
      if (evt.getClickCount() > 1){
         tabbedPane.setSelectedComponent(editarPanel);
         editarButton.setEnabled(false);
         grabarButton.setEnabled(true);
      }
      nuevo = false;
   }//GEN-LAST:event_tablaMouseClicked

   private void tabbedPaneMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tabbedPaneMouseClicked
      editarButton.setEnabled(false);
      grabarButton.setEnabled(tabbedPane.getSelectedComponent().equals(editarPanel));
   }//GEN-LAST:event_tabbedPaneMouseClicked
   @Action
   public void nuevoButtonActionPerformed() {
      try{
         tabbedPane.setSelectedComponent(editarPanel);
         grabarButton.setEnabled(true);
         eliminarButton.setEnabled(false);
         editarButton.setEnabled(false);
         docenteSeleccionado = new Docente();
         codigoTextField.setText("");
         nombreTextField.setText("");
         direccionTextField.setText("");
         tlfTextField.setText("");
         nuevo = true;
      }catch(Exception e){
         JOptionPane.showMessageDialog(this, e.getMessage() + "...!");
      }
   }
   @Action
   public void editarButtonActionPerformed(){
      try{
         tabbedPane.setSelectedComponent(editarPanel);
         editarButton.setEnabled(nuevo);
         eliminarButton.setEnabled(true);
         grabarButton.setEnabled(true);
      }catch(Exception e){
         JOptionPane.showMessageDialog(this, e.getMessage() + "...!");
      }
   }
   @Action
   public void cancelarButtonActionPerformed() {
      try{
         dispose();
      }catch(Exception e){
         JOptionPane.showMessageDialog(this, e.getMessage() + "...!");
      }
   }
   @Action
   public void grabarButtonActionPerformed() {
      try{
         if(docenteSeleccionado == null)  return;
         
         docenteSeleccionado.setDoceNom(nombreTextField.getText());
         docenteSeleccionado.setDoceDir(direccionTextField.getText());
         docenteSeleccionado.setDoceTel1(tlfTextField.getText());
         entityManager.getTransaction().begin();
         if(nuevo)
            entityManager.persist(getDocenteSeleccionado()); 
         else
            entityManager.merge(getDocenteSeleccionado());
         entityManager.getTransaction().commit();
         if(nuevo){
            docenteList.add(docenteSeleccionado);
            tabbedPane.setSelectedIndex(0);
            if(tabla.getRowCount() > 0) mostrarFila(tabla.getRowCount()-1);
         }else{
            docenteList.set(tabla.convertRowIndexToModel(tabla.getSelectedRow()), docenteSeleccionado);
         }
         nuevo = false;
         eliminarButton.setEnabled(false);
         JOptionPane.showMessageDialog(this, docenteSeleccionado.getDoceNom() + " ha sido guardado...!");
      }catch(Exception e){
         JOptionPane.showMessageDialog(this, e.getMessage() + "...!");
         e.printStackTrace();
         entityManager.getTransaction().rollback();
      }
   }
   @Action
   public void eliminarButtonActionPerformed() {
      try{
         Docente aEliminar;
         if(docenteSeleccionado == null || nuevo) return;
         if(seConfirma("¿Confirma la eliminacion de "+docenteSeleccionado.getDoceNom()+"?")){
            aEliminar = entityManager.find(Docente.class, docenteSeleccionado.getDoceCod());
            entityManager.getTransaction().begin();
            entityManager.remove(aEliminar);
            entityManager.getTransaction().commit();
            docenteList.remove(aEliminar);
            docenteSeleccionado = null;
            eliminarButton.setEnabled(false);
         }
      }catch(RollbackException re){
         if(re.getCause() instanceof DatabaseException){
            DatabaseException dEx = (DatabaseException)re.getCause();
            if(dEx.getErrorCode() == 4002){
               JOptionPane.showMessageDialog(this, "El docente aparece en otros registros, no se puede eliminar");
            }
         }else
            JOptionPane.showMessageDialog(this, re.getMessage() + "...!");
      }catch(Exception e){
         if(e instanceof RollbackException) System.out.println("hola luis:D");
         e.printStackTrace();
         JOptionPane.showMessageDialog(this, e.getMessage() + "...!");
         entityManager.getTransaction().rollback();
      }
   }
   
   public boolean textContenidoEn(Object dato){
      char valTabla[];
      char valText[];
      int i, ind, j;
      
      if(dato == null)  return false;
      valTabla = dato.toString().toLowerCase().toCharArray();
      valText = buscarTextField.getText().toLowerCase().toCharArray();
      if(valTabla.length < valText.length) return false;
      for(i = 0; i <= valTabla.length - valText.length; i++){
         ind = i;
         j = 0;
         while(j < valText.length && valTabla[ind] == valText[j]){
            ind++;
            j++;
         }
         if(j == valText.length) return true;
      }
      return false;
   }
   
   private boolean seConfirma(String mensaje){
        int n = JOptionPane.showConfirmDialog(null, mensaje,
                "Aviso", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null);
        return n == JOptionPane.YES_OPTION;
    }
   
   public Docente getDocenteSeleccionado() {
      return docenteSeleccionado;
   }

   public void setDocenteSeleccionado(Docente docenteSeleccionado) {
      Docente old = this.docenteSeleccionado;
      this.docenteSeleccionado = docenteSeleccionado;
      getChangeSupport().firePropertyChange("docenteSeleccionado", old, docenteSeleccionado);
   }

   public PropertyChangeSupport getChangeSupport() {
      if (changeSupport == null) {
         changeSupport = new PropertyChangeSupport(this);
      }
      return changeSupport;
   }
   @Override
   public void addPropertyChangeListener(PropertyChangeListener l) {
      getChangeSupport().addPropertyChangeListener(l);
   }
   @Override
   public void removePropertyChangeListener(PropertyChangeListener l) {
      getChangeSupport().removePropertyChangeListener(l);
   }
   //attributes
   private boolean nuevo;
   private PropertyChangeSupport changeSupport;
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox buscarComboBox;
    private javax.swing.JTextField buscarTextField;
    private javax.swing.JButton cancelButton;
    private javax.swing.JTextField codigoTextField;
    private javax.swing.JTextField direccionTextField;
    private java.util.List<Docente> docenteList;
    private javax.persistence.Query docenteQuery;
    private pe.edu.unmsm.cinfo.siga.datos.Docente docenteSeleccionado;
    private javax.swing.JButton editarButton;
    private javax.swing.JPanel editarPanel;
    private javax.swing.JButton eliminarButton;
    private javax.persistence.EntityManager entityManager;
    private javax.swing.JButton grabarButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JTextField nombreTextField;
    private javax.swing.JButton nuevoButton;
    private javax.swing.JPanel relacionPanel;
    private javax.swing.JScrollPane scrollPane;
    private javax.swing.JTabbedPane tabbedPane;
    private javax.swing.JTable tabla;
    private javax.swing.JTextField tlfTextField;
    private javax.swing.JPanel totalPanel;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
}
